import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:xindong/common/xindong_sezhi.dart';
import 'package:xindong/common/xindong_define.dart';
import 'package:xindong/common/xindong_methods.dart';
import 'package:xindong/handle/xindong_common_handle.dart';
import 'package:xindong/manager/xindong_chat_singleton.dart';
import 'package:xindong/manager/xindong_page_singleton.dart';
import 'package:xindong/models/user/xindong_base_user.dart';
import 'package:xindong/routes/conversation/xindong_liaotian_app_bar.dart';
import 'package:xindong/routes/conversation/xindong_liaotian_setting_yemian.dart';
import 'package:xindong/routes/conversation/view/xindong_liaotian_common_words.dart';
import 'package:xindong/routes/conversation/view/xindong_liaotian_custom_message_container.dart';
import 'package:xindong/routes/conversation/view/xindong_liaotian_message_image_cell.dart';
import 'package:xindong/routes/conversation/view/xindong_liaotian_message_sound_cell.dart';
import 'package:xindong/routes/conversation/view/xindong_liaotian_message_text_cell.dart';
import 'package:xindong/routes/tab_chats/controller/xindong_liaotian_vm.dart';
import 'package:xindong/routes/tab_chats/xindong_chat_message_type.dart';
import 'package:xindong/utils/xindong_text_util.dart';
import 'package:xindong/widgets/xindong_avatar.dart';
import 'package:tencent_cloud_chat_uikit/tencent_cloud_chat_uikit.dart';
import 'package:tencent_cloud_chat_uikit/ui/views/TIMUIKitChat/TIMUIKItMessageList/tim_uikit_chat_history_message_list_config.dart';

import 'custom_tim_uikit_chat.dart';
import 'input/xindong_liaotian_input_controller.dart';
import 'input/xindong_liaotian_input_util.dart';
import 'input/xindong_liaotian_keyboard_controller.dart';

class XinDongLiaoTianYeMian extends StatefulWidget {
  final V2TimConversation conversation;
  final bool fromKongJian;

  const XinDongLiaoTianYeMian({super.key, required this.conversation, required this.fromKongJian});

  @override
  State<XinDongLiaoTianYeMian> createState() => _XinDongLiaoTianYeMianState();
}

class _XinDongLiaoTianYeMianState extends State<XinDongLiaoTianYeMian> {
  static const config = TIMUIKitChatConfig(isUseMessageReaction: true);
  final tipsConfig = ToolTipsConfig(
    showReplyMessage: false,
    showForwardMessage: false,
    showMultipleChoiceMessage: false,
    showTranslation: false,
    showRecallMessage: true,
  );
  final _chatMessageType = XinDongChatMessageType();
  final _coreInstance = TIMUIKitCore.getInstance();

  String? get userId {
    return widget.conversation.userID;
  }

  // 点击头像
  _onTapAvatar(userId) {
    if (widget.fromKongJian == true) {
      Get.back();
    } else {
      final user = XinDongBaseUser();
      user.userid = userId;
      user.user_id = userId;
      XinDongPageSingleton.instance.jumpToSpace(user, isChat: true);
    }
  }

  // 点击右上角按钮
  _onTapMore() {
    if (XinDongChatSingleton.instance.detailClass == null) {
      return;
    }
    XinDongPageSingleton.instance.pushYeMian(XinDongLiaoTianSettingYeMian(
      conversation: widget.conversation,
      detailClass: XinDongChatSingleton.instance.detailClass!,
      onTapAvatar: () => _onTapAvatar(userId),
    ));
  }

  @override
  void initState() {
    super.initState();
    // 成对出现 设置ID
    XinDongLiaoTianVM.to.currentConversationID = widget.conversation.conversationID;
    XinDongChatSingleton.instance.conversation = widget.conversation;
    _coreInstance.setTheme(theme: const TUITheme(chatBgColor: DZColors.backgroundColor));
    WidgetsBinding.instance.addPostFrameCallback((_) async {
      if (TextUtil.isEmpty(userId)) {
        showToast("单聊用户ID为空");
        Get.back();
        return;
      }

      XinDongChatSingleton.instance.getDetails(userId);
      XinDongCommonHandle().chatCommonWords();

      // Provider.of<XinDongKeyBoardClass>(context, listen: false).showKeyboard();
      // Provider.of<XinDongInputTextFieldProvider>(context, listen: false).close();
      // Provider.of<XinDongInputTextFieldProvider>(context, listen: false).closeMiniGames();
      // Provider.of<XinDongInputTextFieldProvider>(context, listen: false).inputController.clear();
      // if (widget.userClass.isAnchor && widget.conversation.lastMessage == null) {
      //   // XinDongMessageHandling.insertLocalMessage(userClass: widget.userClass, type: XinDongCustomMessageType.characterAnchorInformation);
      //   if (XinDongUserProvider.instance.accountUser?.user.gender == Gender.male &&
      //       XinDongUserProvider.instance.accountUser?.userAccountEnity.blueDiamond != null &&
      //       XinDongUserProvider.instance.accountUser!.userAccountEnity.blueDiamond! > 0) {
      //     XinDongMessageHandling.insertLocalMessage(
      //         userClass: widget.userClass,
      //         type: XinDongCustomMessageType.characterReminder,
      //         data: {"content": "聊天过程中如涉及汇款，转账等金钱交易，请谨慎处理，以防被骗导致财产损失，"});
      //   }
      // }
      // if (XinDongDataStorage.getBool(SP_KEY_HINT_DISCOUNT, defValue: true) == true &&
      //     XinDongUserProvider.instance.isShowDiscount) {
      //   XinDongMessageHandling.insertLocalMessage(
      //       userClass: widget.userClass,
      //       type: XinDongCustomMessageType.characterDiscount,
      //       desc: "现在开通会员\n消费打${XinDongGlobal.instance.globalList.discount ?? 9}折哟~");
      //   XinDongDataStorage.saveBool(SP_KEY_HINT_DISCOUNT, false);
      // }
    });
  }

  @override
  void dispose() {
    // 成对出现 取消ID
    XinDongLiaoTianVM.to.currentConversationID = null;
    XinDongChatSingleton.instance.conversation = null;
    XinDongChatSingleton.instance.detailClass = null;
    super.dispose();
  }

  String getTitle() {
    return widget.conversation.showName ?? widget.conversation.userID ?? "";
  }

  // 头像
  Widget userAvatarBuilder(BuildContext context, V2TimMessage message) {
    return XinDongAvatar(url: message.faceUrl, size: 40);
  }

  @override
  Widget build(BuildContext context) {
    // 聊天内容最大宽度，32边距 20间距 80头像+错误图标/未读已读
    final maxWidth = screenWidth - 32 - 20 - 80;
    final _inputController = Get.put(XinDongLiaoTianInputController()); // 聊天输入框控制
    final _keyboardController = Get.put(XinDongLiaoTianKeyBoardController()); // 键盘控制

    final messageItemBuilder = MessageItemBuilder(
      // 文本
      textMessageItemBuilder: (V2TimMessage message, bool isShowJump, VoidCallback clearJump) {
        return XinDongLiaoTianMessageText(message: message, maxWidth: maxWidth);
      },
      // 语音
      soundMessageItemBuilder: (V2TimMessage message, bool isShowJump, Function() clearJump) {
        return XinDongLiaoTianMessageSound(message: message, maxWidth: maxWidth, clearJump: clearJump);
      },
      // 图片
      imageMessageItemBuilder: (V2TimMessage message, bool isShowJump, Function() clearJump) {
        return XinDongLiaoTianMessageImage(message: message);
      },
      customMessageItemBuilder: (V2TimMessage message, bool isShowJump, Function() clearJump) {
        return XinDongLiaoTianCustomMessageContainer(
          message: message,
          maxWidth: maxWidth,
          chatMessageType: _chatMessageType,
          clearJump: clearJump,
          userClass: XinDongChatSingleton.instance.detailClass?.another,
        );
      },
      // 自定义一整行
      messageRowBuilder: (V2TimMessage message, Widget messageWidget, Function onScrollToIndex,
          bool isNeedShowJumpStatus, VoidCallback clearJumpStatus, Function onScrollToIndexBegin) {
        // 聊天消息
        if (_chatMessageType.isChatType(message)) {
          return null;
        } else {
          return XinDongLiaoTianCustomMessageContainer(
            message: message,
            maxWidth: maxWidth,
            chatMessageType: _chatMessageType,
            clearJump: clearJumpStatus,
            userClass: XinDongChatSingleton.instance.detailClass?.another,
          );
        }
      },
    );

    // 1、修改点击隐藏事件GestureDetector
    // XinDongLiaoTianInputController.to.closeAll();
    // XinDongChatSingleton.instance.chatController.textFieldController?.hideAllPanel();
    // 2、修改键盘抬起顶起输入框，注释：resizeToAvoidBottomInset: false,
    //
    return CustomTIMUIKitChat(
      conversation: widget.conversation,
      config: config,
      controller: XinDongChatSingleton.instance.chatController,
      utilTipsConfig: tipsConfig,
      customAppBar: conversationAppBar(title: getTitle(), onTap: _onTapMore),
      onTapAvatar: (uid, details) => _onTapAvatar(widget.conversation.userID),
      messageItemBuilder: messageItemBuilder,
      userAvatarBuilder: userAvatarBuilder,
      mainHistoryListConfig: TIMUIKitHistoryMessageListConfig(padding: const EdgeInsets.only(bottom: 0)),
      topFixWidget: Container(
        color: Colors.white70,
        padding: const EdgeInsets.all(8),
        child: Text.rich(
          TextSpan(text: "一切以", children: [
            const TextSpan(
              text: "刷单、做任务、抢单、点赞、兼职",
              style: TextStyle(color: Colors.red),
            ),
            const TextSpan(
              text: "等赚钱理由，要求加微信或下载其他软件，均为诈骗，请",
            ),
            TextSpan(
              text: "立即举报",
              style: const TextStyle(color: DZColors.mainColor),
              recognizer: TapGestureRecognizer()
                ..onTap = () {
                  XinDongPageSingleton.instance.jumpToReport(userId: userId);
                },
            ),
          ]),
          style: const TextStyle(fontSize: 13, color: DZColors.contentColor),
        ),
      ),
      inputTopBuilder: const XinDongLiaoTianCommonWords(),
      textFieldBuilder: (BuildContext context) {
        return XinDongLiaoTianInputWidget(
          conversation: widget.conversation,
          userId: widget.conversation.userID!,
        );
      },
      // topFixWidget: XinDongLiaoTianAnchorInfoElem(
      //   userClass: widget.userClass,
      //   onTapAvatar: (E) {},
      // ),
    );

    /* return XinDongTIMCustomChat(
        userClass: widget.userClass,
        conversation: widget.conversation,
        config: config,
        onTapAvatar: (uid, details) => _onTapAvatar(widget.userClass),
        utilTipsConfig: ToolTipsConfig(
            showReplyMessage: false,
            showForwardMessage: false,
            showMultipleChoiceMessage: false,
            showTranslation: false,
            showRecallMessage: false),
        messageItemBuilder: messageItemBuilder,
        userAvatarBuilder: userAvatarBuilder,
        mainHistoryListConfig: TIMUIKitHistoryMessageListConfig(padding: EdgeInsets.only(bottom: 20)),
        textFieldBuilder: (BuildContext context) {
          return XinDongLiaoTianInputWidget(
            conversation: widget.conversation,
            userClass: widget.userClass,
          );
        },
        topFixWidget: XinDongLiaoTianAnchorInfoElem(
          userClass: widget.userClass,
          onTapAvatar: (E) {},
        ),
        customAppBar: (model) {
          return chatAppBar(
              userClass: widget.userClass,
              onTapAvatar: (a) {
                // _onTapAvatar(widget.userClass.uid);
              },
              context: context,
              onRemark: (name) {
                setState(() {
                  widget.conversation.showName = name;
                });
              },
              getTitle: getTitle(),
              clearHistory: () => model.clearHistory());
        });*/
  }
}
